﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace Tycho.Peyote {
    public class DragDropHandler {
        private FrameworkElement DragElement = null;
        private bool Dragging = false;
        private bool InDragDrop;
        private Point DragStart;
        private DataObject DataObject = null;

        public DragDropHandler (FrameworkElement dragElement, DataObject dataObject) {
            this.DragElement = dragElement;
            this.DataObject = dataObject;

            dragElement.MouseLeftButtonDown += DragElement_MouseLeftButtonDown;
            dragElement.MouseMove += DragElement_MouseMove;
        }

        void DragElement_MouseLeftButtonDown (object sender, MouseButtonEventArgs e) {
            if (!DragElement.IsMouseCaptured) {
                Dragging = true;
                DragStart = e.GetPosition (DragElement);
            }
        }

        void DragElement_MouseMove (object sender, MouseEventArgs e) {
            if (Dragging) {
                Point currentPos = e.GetPosition (DragElement);

                if ((Math.Abs (currentPos.X - DragStart.X) > SystemParameters.MinimumHorizontalDragDistance)
                    || (Math.Abs (currentPos.Y - DragStart.Y) > SystemParameters.MinimumVerticalDragDistance)) {
                    DragElement.CaptureMouse ();

                    InDragDrop = true;
                    DragDropEffects de = DragDrop.DoDragDrop (DragElement, DataObject, DragDropEffects.Move);
                    InDragDrop = false;
                    Dragging = false;
                    DragElement.ReleaseMouseCapture ();
                }
            }
        }
    }
}
